"use client"

import { useRef, useState } from "react"
import {
    View,
    Text,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    Platform,
    Image,
    Dimensions,
    Modal,
    Alert,
    Animated,
    Pressable,
} from "react-native"
import { BookOpen, X } from "lucide-react-native"
import { LinearGradient } from "expo-linear-gradient"
import { theme } from "../../constants/theme"
import { useRouter } from "expo-router"

const { width, height } = Dimensions.get("window")

// 教材数据
const BOOKS = [
    { id: "1000", name: "1000词", count: 1000, type: "hot", color: "#5B8EF4" },
    { id: "2000", name: "2000词", count: 2000, type: "hot", color: "#34C759" },
    { id: "4000", name: "4000词", count: 4000, type: "hot", color: "#FF9500" },
    { id: "powerup", name: "Power Up", count: 1500, type: "primary", color: "#5B8EF4" },
    { id: "raz", name: "RAZ", count: 3000, type: "primary", color: "#FF3B30" },
    { id: "think", name: "Think", count: 2500, type: "junior", color: "#34C759" },
    { id: "oxford", name: "Oxford Discovery", count: 3500, type: "junior", color: "#5B8EF4" },
    { id: "everybody", name: "Everybody Up", count: 2000, type: "primary", color: "#FF9500" },
    { id: "unlock", name: "UNLOCK", count: 4000, type: "senior", color: "#FF3B30" },
    { id: "hiphip", name: "Hip Hip Hooray", count: 1500, type: "primary", color: "#34C759" },
    { id: "english", name: "English World", count: 3000, type: "junior", color: "#5B8EF4" },
    { id: "look", name: "LOOK", count: 1800, type: "primary", color: "#FF9500" },
    { id: "reading", name: "Reading Explorer", count: 4500, type: "college", color: "#5B8EF4" },
    { id: "magic", name: "新魔法英语", count: 2000, type: "new", color: "#FF3B30" },
    { id: "basic", name: "Basic Reading", count: 2500, type: "primary", color: "#34C759" },
    { id: "world", name: "Our World", count: 3000, type: "primary", color: "#5B8EF4" },
    { id: "phonics", name: "Oxford Phonics", count: 1500, type: "bridge", color: "#FF9500" },
    { id: "minds", name: "Super Minds", count: 2800, type: "primary", color: "#34C759" },
    { id: "big", name: "Big English", count: 3200, type: "primary", color: "#5B8EF4" },
]

// 系列教材数据
const SERIES_BOOKS = [
    {
        id: "re1",
        name: "Reading Explorer 1",
        words: 240,
        level: "初级",
        description: "适合初学者的阅读教材，包含基础词汇和简单句型。",
    },
    {
        id: "re2",
        name: "Reading Explorer 2",
        words: 240,
        level: "初级",
        description: "在第一册基础上增加词汇量和句型复杂度。",
    },
    {
        id: "re3",
        name: "Reading Explorer 3",
        words: 240,
        level: "中级",
        description: "进阶阅读材料，包含更多专业词汇和复杂句型。",
    },
    {
        id: "re4",
        name: "Reading Explorer 4",
        words: 240,
        level: "中级",
        description: "中高级阅读教材，培养批判性思维和分析能力。",
    },
    {
        id: "re5",
        name: "Reading Explorer 5",
        words: 240,
        level: "高级",
        description: "高级阅读教材，包含学术词汇和复杂文章结构。",
    },
    {
        id: "ref",
        name: "Reading Explorer F",
        words: 192,
        level: "高级",
        description: "最高级别阅读教材，为学术和专业阅读做准备。",
    },
]

interface LibraryContentProps {
    activeCategory: string
    onAddToBookshelf: (book: any) => void
    onAddToFavorites?: (book: any) => void
    onSelectBook: (book: any) => void
    isPlanMode?: boolean
}

export default function LibraryContent({
    activeCategory,
    onAddToBookshelf,
    onAddToFavorites,
    onSelectBook,
    isPlanMode = false,
}: LibraryContentProps) {
    const [modalVisible, setModalVisible] = useState(false)
    const [selectedBook, setSelectedBook] = useState(null)
    const [selectedSeries, setSelectedSeries] = useState(null)
    const modalAnimation = useRef(new Animated.Value(0)).current
    const router = useRouter()

    const handleBookPress = (book) => {
        setSelectedBook(book)
        setSelectedSeries("reading") // 假设所有书籍都属于Reading Explorer系列
        setModalVisible(true)
        Animated.timing(modalAnimation, {
            toValue: 1,
            duration: 300,
            useNativeDriver: true,
        }).start()
    }

    const closeModal = () => {
        Animated.timing(modalAnimation, {
            toValue: 0,
            duration: 250,
            useNativeDriver: true,
        }).start(() => {
            setModalVisible(false)
        })
    }

    const handleAddToBookshelf = (book) => {
        Alert.alert("添加到书架", `是否将"${book.name}"添加到我的书架？`, [
            {
                text: "取消",
                style: "cancel",
            },
            {
                text: "确定",
                onPress: () => {
                    onAddToBookshelf({
                        id: book.id,
                        name: book.name,
                        wordCount: book.words,
                    })
                    // 可以添加一个成功提示
                    Alert.alert("添加成功", `"${book.name}"已添加到我的书架`)
                },
            },
        ])
    }

    const handleAddToFavorites = (book) => {
        if (!onAddToFavorites) return

        Alert.alert("添加到收藏本", `是否将"${book.name}"添加到收藏本？`, [
            {
                text: "取消",
                style: "cancel",
            },
            {
                text: "确定",
                onPress: () => {
                    onAddToFavorites({
                        id: book.id,
                        name: book.name,
                        wordCount: book.words,
                    })
                    // 可以添加一个成功提示
                    Alert.alert("添加成功", `"${book.name}"已添加到收藏本`)
                },
            },
        ])
    }

    // 处理选择书籍
    const handleSelectSeriesBook = (book) => {
        closeModal()

        // 直接调用传入的回调函数，而不是自己导航
        onSelectBook({
            id: book.id,
            title: book.name,
            subtitle: `${book.level} · ${book.words}词`,
            mastered: Math.floor(Math.random() * 10),
            learning: Math.floor(Math.random() * 15),
            total: book.words,
        })
    }

    const filteredBooks = BOOKS.filter((book) => (activeCategory === "hot" ? true : book.type === activeCategory))

    // 模态框动画样式
    const modalTranslateY = modalAnimation.interpolate({
        inputRange: [0, 1],
        outputRange: [height, 0],
    })

    return (
        <View style={{ flex: 1 }}>
            {/* 书籍列表 */}
            <ScrollView style={styles.booksContainer} showsVerticalScrollIndicator={false}>
                <View style={styles.booksGrid}>
                    {filteredBooks.map((book) => (
                        <TouchableOpacity
                            key={book.id}
                            style={styles.bookCard}
                            onPress={() => handleBookPress(book)}
                            activeOpacity={0.7}
                        >
                            <View style={[styles.bookCardInner, { backgroundColor: book.color }]}>
                                <View style={styles.bookContent}>
                                    <View style={styles.bookIconContainer}>
                                        <BookOpen size={24} color="#FFFFFF" />
                                    </View>
                                    <Text style={styles.bookName}>{book.name}</Text>
                                </View>
                            </View>
                        </TouchableOpacity>
                    ))}
                </View>
            </ScrollView>

            {/* 底部弹出模态框 */}
            <Modal visible={modalVisible} transparent={true} animationType="none" onRequestClose={closeModal}>
                <View style={styles.modalOverlay}>
                    <Pressable style={styles.modalBackdrop} onPress={closeModal} />
                    <Animated.View
                        style={[
                            styles.modalContent,
                            {
                                transform: [{ translateY: modalTranslateY }],
                            },
                        ]}
                    >
                        <View style={styles.modalHeader}>
                            <View style={styles.modalHandleBar} />
                            <TouchableOpacity style={styles.modalCloseButton} onPress={closeModal}>
                                <X size={20} color={theme.colors.neutral.gray} />
                            </TouchableOpacity>
                        </View>

                        <Text style={styles.modalTitle}>Reading Explorer 系列</Text>
                        <Text style={styles.modalSubtitle}>点击可选择书籍，长按可添加至{isPlanMode ? "收藏本" : "我的书架"}</Text>

                        <ScrollView style={styles.seriesList} showsVerticalScrollIndicator={false}>
                            {SERIES_BOOKS.map((book, index) => (
                                <TouchableOpacity
                                    key={book.id}
                                    style={styles.seriesItem}
                                    onPress={() => handleSelectSeriesBook(book)}
                                    onLongPress={() => (isPlanMode ? handleAddToFavorites(book) : handleAddToBookshelf(book))}
                                    delayLongPress={500}
                                >
                                    <View style={[styles.seriesIconContainer, { backgroundColor: getLevelColor(book.level) }]}>
                                        <Image
                                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341025.png" }}
                                            style={styles.seriesIcon}
                                        />
                                    </View>
                                    <View style={styles.seriesInfo}>
                                        <Text style={styles.seriesName}>{book.name}</Text>
                                        <View style={styles.seriesWordCount}>
                                            <Text style={styles.seriesWordCountText}>{book.words}词</Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            ))}
                        </ScrollView>

                        <View style={styles.modalFooter}>
                            <TouchableOpacity
                                style={styles.addAllButton}
                                onPress={() => {
                                    Alert.alert("添加全部", `是否将所有书籍添加到${isPlanMode ? "收藏本" : "我的书架"}？`, [
                                        {
                                            text: "取消",
                                            style: "cancel",
                                        },
                                        {
                                            text: "确定",
                                            onPress: () => {
                                                // 添加所有书籍的逻辑
                                                SERIES_BOOKS.forEach((book) => {
                                                    if (isPlanMode && onAddToFavorites) {
                                                        onAddToFavorites({
                                                            id: book.id,
                                                            name: book.name,
                                                            wordCount: book.words,
                                                        })
                                                    } else {
                                                        onAddToBookshelf({
                                                            id: book.id,
                                                            name: book.name,
                                                            wordCount: book.words,
                                                        })
                                                    }
                                                })
                                                closeModal()
                                                Alert.alert("添加成功", `所有书籍已添加到${isPlanMode ? "收藏本" : "我的书架"}`)
                                            },
                                        },
                                    ])
                                }}
                            >
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 1 }}
                                    style={styles.addAllButtonGradient}
                                >
                                    <Text style={styles.addAllButtonText}>添加全部到{isPlanMode ? "收藏本" : "书架"}</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                    </Animated.View>
                </View>
            </Modal>
        </View>
    )
}

// 辅助函数：根据级别返回对应的颜色
function getLevelColor(level) {
    switch (level) {
        case "初级":
            return theme.colors.secondary.green.default
        case "中级":
            return theme.colors.secondary.orange.default
        case "高级":
            return theme.colors.primary.default
        default:
            return theme.colors.neutral.gray
    }
}

const styles = StyleSheet.create({
    // 书籍列表样式
    booksContainer: {
        flex: 1,
        padding: theme.spacing.lg,
        backgroundColor: theme.colors.neutral.background,
    },
    booksGrid: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "space-between",
    },
    bookCard: {
        width: "48%",
        marginBottom: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.15)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.8,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    bookCardInner: {
        height: 120,
        justifyContent: "center",
        alignItems: "center",
        borderRadius: theme.borderRadius.large,
    },
    bookContent: {
        alignItems: "center",
        justifyContent: "center",
    },
    bookIconContainer: {
        width: 50,
        height: 50,
        borderRadius: 25,
        backgroundColor: "rgba(255, 255, 255, 0.3)",
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.md,
    },
    bookName: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
        textAlign: "center",
    },
    // 模态框样式
    modalOverlay: {
        flex: 1,
        justifyContent: "flex-end",
    },
    modalBackdrop: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "rgba(0, 0, 0, 0.5)",
    },
    modalContent: {
        backgroundColor: theme.colors.neutral.white,
        borderTopLeftRadius: theme.borderRadius.extraLarge,
        borderTopRightRadius: theme.borderRadius.extraLarge,
        paddingBottom: Platform.OS === "ios" ? 34 : 24, // 为底部安全区域留出空间
        height: height * 0.8, // 模态框高度为屏幕高度的80%
    },
    modalHeader: {
        alignItems: "center",
        paddingVertical: theme.spacing.md,
        position: "relative",
    },
    modalHandleBar: {
        width: 40,
        height: 5,
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: 2.5,
    },
    modalCloseButton: {
        position: "absolute",
        right: theme.spacing.lg,
        top: theme.spacing.md,
        padding: theme.spacing.sm,
    },
    modalTitle: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        textAlign: "center",
        marginTop: theme.spacing.sm,
    },
    modalSubtitle: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginTop: theme.spacing.xs,
        marginBottom: theme.spacing.lg,
    },
    seriesList: {
        paddingHorizontal: theme.spacing.lg,
    },
    seriesItem: {
        flexDirection: "row",
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    seriesIconContainer: {
        width: 60,
        height: 60,
        borderRadius: 12,
        alignItems: "center",
        justifyContent: "center",
        marginRight: theme.spacing.lg,
    },
    seriesIcon: {
        width: 30,
        height: 30,
        tintColor: theme.colors.neutral.white,
    },
    seriesInfo: {
        flex: 1,
        justifyContent: "center",
    },
    seriesName: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.xs,
    },
    seriesWordCount: {
        backgroundColor: theme.colors.neutral.lightGray,
        alignSelf: "flex-start",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.xs,
        borderRadius: theme.borderRadius.medium,
    },
    seriesWordCountText: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
    },
    modalFooter: {
        padding: theme.spacing.lg,
    },
    addAllButton: {
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
    },
    addAllButtonGradient: {
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    addAllButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
})

